/**
 * 
 */
package ae.pcfc.cldos.online.web.controller.admin.general.review;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import ae.pcfc.cldos.online.common.ConstantsCommon.Steps;
import ae.pcfc.cldos.online.common.UltimusConstants.AdminDecision;
import ae.pcfc.cldos.online.common.delegate.CompanyAdminDelegate;
import ae.pcfc.cldos.online.common.delegate.EmploymentVisaDelegate;
import ae.pcfc.cldos.online.common.delegate.FnpGSDelegate;
import ae.pcfc.cldos.online.common.exception.EmployeeAllreadyExistException;
import ae.pcfc.cldos.online.common.exception.EmployeeIsBanedException;
import ae.pcfc.cldos.online.common.exception.InsufficientBGException;
import ae.pcfc.cldos.online.common.exception.InvalidClientException;
import ae.pcfc.cldos.online.common.exception.LicenseErrorRemarkException;
import ae.pcfc.cldos.online.common.exception.LicenseExpiredException;
import ae.pcfc.cldos.online.common.exception.PaymentException;
import ae.pcfc.cldos.online.common.exception.QoutaAllowedException;
import ae.pcfc.cldos.online.common.exception.QoutaReqAllowedException;
import ae.pcfc.cldos.online.common.exception.UltimusAppException;
import ae.pcfc.cldos.online.common.exception.UpdateClientDtlException;
import ae.pcfc.cldos.online.common.vo.AdminDecisionVO;
import ae.pcfc.cldos.online.common.vo.AppSaveResponseVO;
import ae.pcfc.cldos.online.common.vo.CommentsVO;
import ae.pcfc.cldos.online.common.vo.EmployeVisaVO;
import ae.pcfc.cldos.online.common.vo.FileVO;
import ae.pcfc.cldos.online.common.vo.UserVO;
import ae.pcfc.cldos.online.common.vo.employee.details.AddressDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.EmployeeDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.PassportDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.PersonalDetailsVO;
import ae.pcfc.cldos.online.fnp.service.client.vo.FNPCatalogVO;
import ae.pcfc.cldos.online.fnp.service.client.vo.FNPParameterVO;
import ae.pcfc.cldos.online.gs.ConstantsGS;
import ae.pcfc.cldos.online.web.Constants;
import ae.pcfc.cldos.online.web.PageType;
import ae.pcfc.cldos.online.web.ViewPath;
import ae.pcfc.cldos.online.web.ViewUtils;
import ae.pcfc.cldos.online.web.controller.base.BaseNewVisaController;
import ae.pcfc.cldos.online.web.model.EmploymentVisaLicenseInfo;
import ae.pcfc.cldos.online.web.services.breadcrumbs.BreadCrumbsFactoryService;
import ae.pcfc.cldos.online.web.services.fnp.FnpParametersCheckService;

/**
 * @author Abed
 *
 */
@Controller
@RequestMapping(value = ViewPath.__ADMIN_EMPLOYMENT_VISA_REVIEW)
public class AdminEmploymentVisaReviewController extends BaseNewVisaController{
	
	@Autowired
	@Qualifier("employmentVisaDelegate")
	private EmploymentVisaDelegate employmentVisaDelegate;
	
	@Autowired
	@Qualifier("companyAdminDelegate")
	private CompanyAdminDelegate companyAdminDelegate;
	
	private FnpGSDelegate FnpGSDelegate;
	@Resource(name = "FnpGSDelegate")
	public void setFnpGSDelegate(FnpGSDelegate FnpGSDelegate) {
		this.FnpGSDelegate = FnpGSDelegate;
	}
	
	@Autowired
	private FnpParametersCheckService fnpParametersCheckService;
	
	@ModelAttribute
	public void populateBreadCrumbs(ModelMap model, @RequestParam String appId) {
		breadCrumbsFactoryService.populateMainAdminRewiewBreadcrumb(model, appId, BreadCrumbsFactoryService.TASK_TYPE_MAIN_ADMIN_APPROVE);
	}
	
	@ModelAttribute(Constants.__COMPANY_EMPLOYMENT_VISA_REVIEWER_LICENSE_INFO_REQUEST_MODEL_KEY)
	public EmploymentVisaLicenseInfo populateRegisterEmploymentVisaReviewerInfoModel(@RequestParam String appId,
			HttpServletRequest request, ModelMap model) throws Exception {
		EmploymentVisaLicenseInfo employmentVisaInfo = new EmploymentVisaLicenseInfo();
		
		EmployeVisaVO employeVisaVO = employmentVisaDelegate
				.getEmployeeVisaDetailByAppId(encryptionDelegate.decodeAndDecrypt(appId), getUserVO(), Steps.MAIN_ADMIN_APPROVE);
		
		AddressDetailsVO addressDetailsVO = employeVisaVO.getAddressDetailsVO();
		mapper.map(addressDetailsVO, employmentVisaInfo);
		CommentsVO commentsVO = employeVisaVO.getCommentsVO();
		mapper.map(commentsVO, employmentVisaInfo);
		EmployeeDetailsVO employeeDetailsVO = employeVisaVO.getEmployeeDetailsVO();
		mapper.map(employeeDetailsVO, employmentVisaInfo);
		PassportDetailsVO passportDetailsVO = employeVisaVO.getPassportDetailsVO();
		mapper.map(passportDetailsVO, employmentVisaInfo);
		PersonalDetailsVO personalDetailsVO = employeVisaVO.getPersonalDetailsVO();
		mapper.map(personalDetailsVO, employmentVisaInfo);
		
		List<FileVO> fileVOList = employeVisaVO.getFileVOList();
		
		model.put("files", fileVOList);
		model.put("comments", employeVisaVO.getApplicationCommentVOs());
		model.put("bgRequired", ConstantsGS.__BG_EMP_VISA);
		
		return employmentVisaInfo;
	}
	
	//Added by Asna for including the FNP Details
	@ModelAttribute(Constants.__FNP_CATALOG_MODEL_KEY)
	public List<FNPCatalogVO> populateFinanceReviewerInfoModel(
			@ModelAttribute(value = Constants.__COMPANY_EMPLOYMENT_VISA_REVIEWER_LICENSE_INFO_REQUEST_MODEL_KEY) EmploymentVisaLicenseInfo employmentVisaLicenseInfo,
			HttpServletRequest request) {
		return FnpGSDelegate.getFnpCatalogVOsByServiceCode(employmentVisaLicenseInfo.getEmployeeSource().toString());
		
	}
	
	//added by asna end
	
	@RequestMapping(value = "/form.htm", method = RequestMethod.GET)
	public ModelAndView form() {
		return ViewUtils.DEFAULT_VIEW;
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/form.htm")
	public ModelAndView form(
			HttpServletRequest request,
			SessionStatus status,
			@RequestParam String appId,
			@RequestParam String fnpServiceCode,
			@ModelAttribute(value = Constants.__COMPANY_EMPLOYMENT_VISA_REVIEWER_LICENSE_INFO_REQUEST_MODEL_KEY) EmploymentVisaLicenseInfo employmentVisaLicenseInfo,
			BindingResult errors) throws Exception {
		
		System.out.println("review process submitted");
		UserVO userVO = getUserVO();
		AdminDecisionVO adminDecisionVO = new AdminDecisionVO();
		Map<String, String> paramMap = new HashMap<String, String>();
		
		String adminComments = employmentVisaLicenseInfo.getAdminComments();
		
		boolean isSubmitApproval = WebUtils.hasSubmitParameter(request, "MainUserApprove");
		boolean isSubmitReject = WebUtils.hasSubmitParameter(request, "MainUserReject");
		boolean isSubmitCancel = WebUtils.hasSubmitParameter(request, "MainUserCancel");
		
		if(isSubmitApproval){
			System.out.println("Main admin Approved...");
			adminDecisionVO.setStrActionType(AdminDecision.APPROVED.getAdminDecision());
		}else if(isSubmitReject){
			if(adminComments==null || adminComments.isEmpty()){
				errors.reject("admin.comment.required");
			}
			System.out.println("Main admin Rejected...");
			adminDecisionVO.setStrActionType(AdminDecision.REJECTED.getAdminDecision());
		} else if(isSubmitCancel){
			System.out.println("Main admin Canceled...");
			adminDecisionVO.setStrActionType(AdminDecision.CANCELLED.getAdminDecision());
		}
		
		if(!errors.hasErrors()){
			if(isSubmitApproval){
				List<FNPParameterVO> allParams = FnpGSDelegate.retreiveFNPParameters(Arrays.asList(new String[]{fnpServiceCode}));
				List<FNPParameterVO> notFeeled = fnpParametersCheckService.feelParamsAndGetNotFeeled(request, allParams);
				if(notFeeled.size()>0){
					errors.reject("sdgsd", "Recomplete payment info please");
				} else {
					adminDecisionVO.setFnpParams(allParams);
				}
			}
			adminDecisionVO.setApplicationId(encryptionDelegate.decodeAndDecrypt(appId));
			adminDecisionVO.setUserVO(userVO);
			adminDecisionVO.setFnpServiceCode(fnpServiceCode);
			adminDecisionVO.setComment(adminComments);
			
			try{
				AppSaveResponseVO appSaveResponseVO = companyAdminDelegate.companyAdminAction(adminDecisionVO);
				paramMap.put(Constants.__REFRENCE_NO, appSaveResponseVO.getReferenceNo());
				paramMap.put(Constants.__INCIDENT_NO, appSaveResponseVO.getIncidentNo());
			}catch (PaymentException e) {
				errors.reject("error.payment");
			}catch (LicenseErrorRemarkException e) {
				errors.reject("license.errorremark");
			}catch (LicenseExpiredException e) {
				errors.reject("license.expire");
			}catch (EmployeeAllreadyExistException e) {
				errors.reject("employee.exist");
			} catch (EmployeeIsBanedException e) {
				errors.reject("employee.baned");
			}catch (QoutaAllowedException e) {
				errors.reject("act.emp.more.than.allowed");
			}catch (QoutaReqAllowedException e) {
				errors.reject("act.emp.more.than.reqallowed");
			}catch(InsufficientBGException e){
				errors.reject("insufficient.bg");
			}catch(InvalidClientException e){
				errors.reject("invalid.client");
			}catch(UpdateClientDtlException e){
				e.printStackTrace();
				errors.reject("update.client.dtls");
			}catch(UltimusAppException e){
				e.printStackTrace();
				errors.reject("unable.to.proceed.ultimus.down");
			}catch(Exception e){
				e.printStackTrace();
				errors.reject("unable.to.proceed");
			}
		
		}
		if(!errors.hasErrors()){
			return new ModelAndView(ViewUtils.getRedirect(ViewPath.__CONFIRMATION, PageType.SHOW, paramMap));
		} else {
			return ViewUtils.DEFAULT_VIEW;
		}

	}
	
}
